/*
 * Counter.h
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#pragma once

class Counter
{
public:
    enum OperationMode
    {
        SINGLE,
        LOOP,
        OSCILLATE
    };

public:
    Counter(unsigned int period = 0, OperationMode mode = SINGLE)
        : _period(period),
          _mode(mode),
          _counter(0),
          _delta(1),
          _step(1)
    {}

    void tick()
    {
        if (hit())
        {
            switch (_mode)
            {
            case LOOP:
                restart();
                return;
            case OSCILLATE:
                _delta = -_delta;
                break;
            default:
                return;
            };
        }

        if (_mode == OSCILLATE && _counter <= 0 && _delta < 0)
        {
            _delta = -_delta;
        }

        _counter += _delta * _step;
    }

    bool hit() const
    {
        return _period ? _counter >= _period - 1 : false;
    }

    void restart() { _counter = 0; }
    void stop()    { _counter = _period; }

    void set(unsigned int value)         { _counter = value; }
    void set_period(unsigned int period) { _period = period; }
    void set_step(unsigned int step)     { _step = step; }

    unsigned int get() const    { return _counter; }
    unsigned int period() const { return _period; }
    unsigned int step() const   { return _step; }
    int delta() const           { return _step * _delta; }

private:
    OperationMode _mode;
    unsigned int _period;
    unsigned int _counter;
    unsigned int _step;
    int _delta;
};

